package com.googlecode.springgameengine.lwjgl;

import com.googlecode.springgameengine.Scene;
import com.googlecode.springgameengine.actor.Actor;
import com.googlecode.springgameengine.rendering.ActorRendererResolver;
import com.googlecode.springgameengine.rendering.Renderer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import static org.lwjgl.opengl.GL11.*;

/**
 *
 * @author Maciej
 */
public class LWJGLRenderer implements Renderer {

	private static final Log log = LogFactory.getLog(LWJGLRenderer.class);
	private ActorRendererResolver actorRendererResolver;
	private int maxFps = 60;

	@Override
	public void init() {
		try {
			Display.setDisplayMode(new DisplayMode(800, 600));
			Display.create();
		} catch (LWJGLException ex) {
			log.fatal("LWJGLRenderer initialization error!", ex);
		}
	}

	@Override
	public void render(Scene scene) {
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
		for (Actor actor : getSceneActors(scene)) {
			actorRendererResolver.render(actor);
		}

		Display.update();
		Display.sync(maxFps);
	}

	@Override
	public void destroy() {
		Display.destroy();
	}

	/**
	 * For future optimizations
	 *
	 * @param scene
	 * @return
	 */
	protected Iterable<Actor> getSceneActors(Scene scene) {
		return scene.getActors();
	}

	public int getMaxFps() {
		return maxFps;
	}

	public void setMaxFps(int desiredFps) {
		this.maxFps = desiredFps;
	}

	public ActorRendererResolver getActorRendererResolver() {
		return actorRendererResolver;
	}

	public void setActorRendererResolver(ActorRendererResolver actorRendererResolver) {
		this.actorRendererResolver = actorRendererResolver;
	}
}
